<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="房间号" prop="roomNumber">
        <el-input
          v-model="queryParams.roomNumber"
          placeholder="请输入房间号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="roomStatus">
        <el-select v-model="queryParams.roomStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.apartment_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="户型" prop="roomSchema">
        <el-select v-model="queryParams.roomSchema" placeholder="请选择户型" clearable>
          <el-option
            v-for="dict in dict.type.room_h"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="家装" prop="roomDecoration">
        <el-select v-model="queryParams.roomDecoration" placeholder="请选择家装" clearable>
          <el-option
            v-for="dict in dict.type.room_d"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="阳台" prop="roomBalcony">
        <el-select v-model="queryParams.roomBalcony" placeholder="请选择阳台" clearable>
          <el-option
            v-for="dict in dict.type.room_y"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="租金" prop="roomRent">
        <el-input
          v-model="queryParams.roomRent"
          placeholder="请输入租金"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房间面积" prop="roomArea">
        <el-input
          v-model="queryParams.roomArea"
          placeholder="请输入房间面积"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="所属公寓id" label-width="80" prop="apartmentId">-->
<!--        <el-input-->
<!--          v-model="queryParams.apartmentId"-->
<!--          placeholder="请输入所属公寓id"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="所属公寓" prop="apartmentNickname">
        <el-input
          v-model="queryParams.apartmentNickname"
          placeholder="请输入公寓名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['room:room:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['room:room:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['room:room:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['room:room:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="房间id" align="center" prop="roomId" />-->
      <el-table-column label="房间号" align="center" prop="roomNumber" />
      <el-table-column label="状态" align="center" prop="roomStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.apartment_state" :value="scope.row.roomStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="图片信息" align="center" prop="roomImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.roomImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="户型" align="center" prop="roomSchema">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.room_h" :value="scope.row.roomSchema"/>
        </template>
      </el-table-column>
      <el-table-column label="家装" align="center" prop="roomDecoration">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.room_d" :value="scope.row.roomDecoration"/>
        </template>
      </el-table-column>
      <el-table-column label="阳台" align="center" prop="roomBalcony">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.room_y" :value="scope.row.roomBalcony"/>
        </template>
      </el-table-column>
      <el-table-column label="租金" align="center" prop="roomRent">
        <template slot-scope="scope">
          {{ formatRent(scope.row.roomRent) }}
        </template>
      </el-table-column>

      <el-table-column label="房间面积" align="center" prop="roomArea">
        <template slot-scope="scope">
          {{ formatArea(scope.row.roomArea) }}
        </template>
      </el-table-column>
<!--      <el-table-column label="所属公寓id" align="center"  prop="apartmentId" />-->

      <el-table-column label="所属公寓" align="center" prop="apartmentNickname" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['room:room:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['room:room:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改房间属性管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="房间号" prop="roomNumber">
          <el-input v-model="form.roomNumber" placeholder="请输入房间号）" />
        </el-form-item>
        <el-form-item label="状态" prop="roomStatus">
          <el-select v-model="form.roomStatus" placeholder="请选择状态">
            <el-option
              v-for="dict in dict.type.apartment_state"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片信息" prop="roomImage">
          <image-upload v-model="form.roomImage"/>
        </el-form-item>
        <el-form-item label="户型" prop="roomSchema">
          <el-select v-model="form.roomSchema" placeholder="请选择户型">
            <el-option
              v-for="dict in dict.type.room_h"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼层" prop="roomFloor">
          <el-input v-model="form.roomFloor" placeholder="请输入楼层号）" />
        </el-form-item>
        <el-form-item label="家装" prop="roomDecoration">
          <el-select v-model="form.roomDecoration" placeholder="请选择家装">
            <el-option
              v-for="dict in dict.type.room_d"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阳台" prop="roomBalcony">
          <el-select v-model="form.roomBalcony" placeholder="请选择阳台">
            <el-option
              v-for="dict in dict.type.room_y"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="租金" prop="roomRent">
          <el-input v-model="form.roomRent" placeholder="请输入租金">
            <template slot="append">元/月</template>
          </el-input>
        </el-form-item>
        <el-form-item label="房间面积" prop="roomArea">
          <el-input v-model="form.roomArea" placeholder="请输入房间面积">
            <template slot="append">平方米</template>
          </el-input>
        </el-form-item>
<!--        <el-form-item label="公寓id" prop="apartmentId">-->
<!--          <el-input v-model="form.apartmentId" placeholder="请输入所属公寓id" />-->
<!--        </el-form-item>-->
        <el-form-item label="所属公寓" prop="apartmentNickname">
          <el-select v-model="form.apartmentNickname" placeholder="请选择所属公寓" @change="handleApartmentChange">
            <el-option
              v-for="item in apartmentOptions"
              :key="item.apartmentId"
              :label="item.apartmentName"
              :value="item.apartmentName"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRoom, getRoom, delRoom, addRoom, updateRoom,listApartment } from "@/api/room/room";

export default {
  name: "Room",
  dicts: ['room_h', 'room_y', 'apartment_state', 'room_d'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房间属性管理表格数据
      roomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      apartmentOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roomNumber: null,
        roomStatus: null,
        roomSchema: null,
        roomDecoration: null,
        roomBalcony: null,
        roomRent: null,
        roomArea: null,
        apartmentId: null,
        apartmentNickname: null
      },
      // 表单参数
      form: {
        apartmentId: null,
        apartmentNickname: null
      },
      // 表单校验
      rules: {
        roomNumber: [
          { required: true, message: "房间号不能为空", trigger: "blur" },
          { validator: this.validateRoomNumber, trigger: "blur" }
        ],
        roomStatus: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        roomSchema: [
          { required: true, message: "户型不能为空", trigger: "change" }
        ],
        roomFloor: [
          { required: true, message: "楼层不能为空", trigger: "blur" },
          { validator: this.validateFloor, trigger: "blur" }
        ],
        roomDecoration: [
          { required: true, message: "家装不能为空", trigger: "change" }
        ],
        roomBalcony: [
          { required: true, message: "阳台不能为空", trigger: "change" }
        ],
        roomRent: [
          { required: true, message: "租金不能为空", trigger: "blur" },
          { validator: this.validateRent, trigger: "blur" }
        ],
        roomArea: [
          { required: true, message: "房间面积不能为空", trigger: "blur" },
          { validator: this.validateArea, trigger: "blur" }
        ],
        apartmentId: [
          { required: true, message: "所属公寓id不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.loadApartmentOptions();
  },
  methods: {
    handleApartmentChange(value) {
      const selectedApartment = this.apartmentOptions.find(apt => apt.apartmentName === value);
      if (selectedApartment) {
        this.form.apartmentId = selectedApartment.apartmentId;
      }
    },
    loadApartmentOptions() {
      listApartment().then(response => {
        this.apartmentOptions = response.rows.map(apt => ({
          apartmentId: apt.apartmentId,
          apartmentName: apt.apartmentName || apt.apartmentNickname // 使用 apartmentName 或 apartmentNickname，取决于你的后端返回的字段名
        }));
        console.log('Apartment options:', this.apartmentOptions); // 添加这行来调试
      }).catch(error => {
        console.error('Error loading apartment options:', error);
      });
    },
    formatRent(rent) {
      return rent ? `${rent} 元/月` : '';
    },
    formatArea(area) {
      return area ? `${area} 平方米` : '';
    },
    validateArea(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入房间面积'));
      } else {
        const num = parseInt(value);
        if (isNaN(num) || num < 0 || num > 9999999 || !Number.isInteger(num)) {
          callback(new Error('请输入正确房间面积'));
        } else {
          callback();
        }
      }
    },
    validateRent(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入租金'));
      } else {
        const num = parseFloat(value);
        if (isNaN(num) || num < 0 || num > 999999999) {
          callback(new Error('请输入正确租金'));
        } else {
          callback();
        }
      }
    },
    validateFloor(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入楼层'));
      } else {
        const num = parseInt(value);
        if (isNaN(num) || num < -6 || num > 120 || !Number.isInteger(num)) {
          callback(new Error('请输入正确楼层号'));
        } else {
          callback();
        }
      }
    },
    validateRoomNumber(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入房间号'));
      } else {
        const num = parseInt(value);
        if (isNaN(num) || num < 100 || num > 10000 || !Number.isInteger(num)) {
          callback(new Error('请输入正确房间号（402，501）'));
        } else {
          callback();
        }
      }
    },
    /** 查询房间属性管理列表 */
    getList() {
      this.loading = true;
      listRoom(this.queryParams).then(response => {
        this.roomList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        roomId: null,
        roomNumber: null,
        roomStatus: null,
        roomImage: null,
        roomSchema: null,
        roomFloor: null,
        roomDecoration: null,
        roomBalcony: null,
        roomRent: null,
        isDeleted: null,
        roomArea: null,
        apartmentId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roomId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加房间属性管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const roomId = row.roomId || this.ids
      getRoom(roomId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改房间属性管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // ... 其他数据处理
          if (this.form.roomId != null) {
            updateRoom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRoom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roomIds = row.roomId || this.ids;
      this.$modal.confirm('是否确认删除房间属性管理编号为"' + roomIds + '"的数据项？').then(function () {
        return delRoom(roomIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('room/room/export', {
        ...this.queryParams
      }, `room_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
